/**
 * 
 * 下载文件
 * ios手机直接打开文件，手动存储文件到手机，Android手机从根目录创建文件夹
 * Android手机文件保存的位置不易查找, 将文件保存在 ‘file://storage/emulated/0/盐城湿地大保护/’
 * 
 */

function fSetFileName(sFilePath, url, fileName) {
	// 获取文件名称
	let name = '';
	for (let i = 0; i < fileName.length; i++) {
		console.log(url , fileName[i].accessoryUrl);
		if (url == fileName[i].accessoryUrl) {
			name = fileName[i].accessoryName;
		}
	}
	let dtask = plus.downloader.createDownload(url, {
			filename: `file://storage/emulated/0/盐城湿地大保护/${name}` //在手机存储更目录创建一个文件夹，把文件存储进去，并更改会原名
		},
		(d, status) => {
			if (status == 200) {
				let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
			} else {
				plus.downloader.clear(); //清除下载任务
			}
		})
	dtask.start();
}

let lock = true;

function downOrOpen(url, i, length, fileName) {
	console.log(url);
	//获取地址后缀
	let suffix = url.substring(url.length - 3);
	let idx = i ? `第${i+1}个` : "";
	//判断是否为（图片或视频）
	if (suffix == "MP4" || suffix == "mp4" || suffix == "jpg" || suffix == "png") {

		const downloadTask = uni.downloadFile({
			url,
			success: res => {
				if (res.statusCode === 200) {
					if (res.tempFilePath.substring(res.tempFilePath.length - 3) == "mp4" || res
						.tempFilePath.substring(res.tempFilePath.length - 3) == "MP4") { //视频
						//保存视频到相册
						uni.saveVideoToPhotosAlbum({
							filePath: res.tempFilePath,
							success: function() {
								uni.showToast({
									title: `${idx}保存成功`,
									icon: 'seccess',
									duration: 1000,
									mask: true
								});
							},
							fail: function(err) {
								console.log(err);
								// this.loadProgress = 0;
								uni.showToast({
									title: `${idx}保存失败`,
									icon: 'error',
									duration: 1000,
									mask: true
								});
							}
						});
					} else { //图片
						// 图片保存到手机相册
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: function() {
								uni.showToast({
									title: `${idx}保存成功`,
									icon: 'success',
									duration: 1000,
									mask: true
								});
							},
							fail: function(err) {
								console.log(err);
								// this.loadProgress = 0;
								uni.showToast({
									title: `${idx}失败成功`,
									icon: 'error',
									duration: 1000,
									mask: true
								});
							}
						});
					}
				} else {
					console.log(res);
					uni.showToast({
						title: `${idx}下载失败`,
						icon: "error",
						duration: 1000,
						mask: true
					})
				}
			},
			fail: (err) => {
				console.log(err);
				uni.showToast({
					icon: "error",
					mask: true,
					title: `${idx}下载失败`,
					duration: 1000
				});
			}
		});
		downloadTask.onProgressUpdate((res) => {
			console.log(res.progress, lock);
			if (res.progress == 100) {
				uni.hideLoading();
				lock = true;
			} else {
				if (lock) {
					uni.showLoading({
						title: `下载中……`,
					})
					lock = false;
				}
			}
		})
	} else {
		//下载文件为非图片和视频的文件
		// let _this = this;

		const downloadTaskt = uni.downloadFile({
			url, //下载地址接口返回
			success: (data) => {
				uni.hideLoading()
				if (data.statusCode === 200) {
					var sFilePath = data.tempFilePath
					var sFileName = url.split('/')[url.split('/').length - 1]; //原来的文件名
					//文件保存到本地
					uni.saveFile({
						tempFilePath: data.tempFilePath, //临时路径
						success: function(res) {
							var savedFilePath = res.savedFilePath;
							let osname = plus.os.name;
							//ios手机直接打开文件，手动存储文件到手机，Android手机从根目录创建文件夹
							if (osname == 'Android') {
								uni.showToast({
									icon: 'success',
									mask: true,
									title: `${idx}保存成功`,
									duration: 1000,
								});
								console.log(idx, fileName, fileName[idx], '+++++++++++++');
								fSetFileName(res.savedFilePath, url, fileName);
							} else {
								setTimeout(() => {
									//打开文档查看
									uni.openDocument({
										filePath: res.savedFilePath,
										success: function(res) {
											console.log("成功打开文件")
										},
										fail(err) {
											console.log(err);
											console.log("打开文件失败")
										}
									})
								}, 1000)
							}
						},
						fail: function(err) {
							console.log(err);
						}
					});

				} else {
					console.log(data);
					uni.showToast({
						icon: "error",
						mask: true,
						title: `${idx}下载失败`,
					})
				}
			},
			fail: (err) => {
				console.log(err);
				uni.showToast({
					icon: "error",
					mask: true,
					title: `${idx}下载失败`,
				})
			}
		})

		downloadTaskt.onProgressUpdate((res) => {
			if (res.progress == 100) {
				uni.hideLoading();
				lock = true;
			} else {
				if (lock) {
					uni.showLoading({
						title: `下载中……`,
					})
					lock = false;
				}
			}
		})
	}
}

export function downLoadFiles(fileUrl, fileName) {
	// 判断传入的是不是数组？
	let fileType = typeof fileUrl;
	let _this = this;
	if (fileType == 'object') {
		for (let i = 0; i < fileUrl.length; i++) {
			downOrOpen(fileUrl[i], i, fileUrl.length, fileName);
		}
	} else if (fileType == 'string') {
		downOrOpen(fileUrl, undefined, undefined, fileName);
	}
}